﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;

namespace Remofi
{
    public partial class MainForm : Form
    {
        MicroServerCore msc;
        public MainForm()
        {
            InitializeComponent();
            string hostName = Dns.GetHostName();
            IPAddress[] ipa = Dns.GetHostAddresses(hostName);
            foreach (IPAddress ip in ipa)
            {
                if (ip.ToString().StartsWith("10.") ||
                    ip.ToString().StartsWith("192."))
                {
                    cmbBoxIP.Items.Add(ip);
                    cmbBoxIP.SelectedItem = ip;
                }
            }
            txtPort.Text = "1688";
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            if (msc != null)
            {
                msc.Stop();
                msc = null;
            }
            else
            {
                try
                {
                    var ip = cmbBoxIP.SelectedItem;
                    msc = new MicroServerCore((IPAddress)cmbBoxIP.SelectedItem, Convert.ToInt32(txtPort.Text));
                    btnStop.Enabled = true;
                    btnStart.Enabled = false;
                    lblMessage.Text =
                        string.Format(@"http://{0}:{1}", 
                            cmbBoxIP.SelectedItem.ToString(), txtPort.Text);
                }
                catch(Exception ex)
                {
                    MessageBox.Show("Initialize failed : {0}", ex.Message);
                }
            }
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            if (msc != null)
            {
                msc.Stop();
                msc = null;
                btnStart.Enabled = true;
                btnStop.Enabled = false;
            }
            lblMessage.Text = string.Empty;
        }

        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (msc != null)
            {
                msc.Stop();
                msc = null;
            }
        }
    }
}
